require('dotenv').config(); // 加载环境变量

const express = require('express');
const cors = require('cors');
const { authMiddleware } = require('./middleware/auth');

// 导入路由
const projectRoutes = require('./routes/projects');        // 项目管理相关路由
const taskRoutes = require('./routes/tasks');              // 任务管理相关路由
const logRoutes = require('./routes/logs');                // 系统日志记录相关路由
const userRoutes = require('./routes/users');              // 用户管理和认证相关路由
const modulesRouter = require('./routes/modules');         // 项目模块管理相关路由
const bugsRouter = require('./routes/bugs');               // 缺陷（Bug）跟踪和管理相关路由
const settingsRouter = require('./routes/settings');       // 系统和用户设置相关路由
const performanceRouter = require('./routes/performance'); // 性能评估和统计相关路由
const projectMembersRouter = require('./routes/project_members'); // 项目成员管理相关路由
const bugCommentsRouter = require('./routes/bug_comments'); // 缺陷评论和讨论相关路由
const moduleAssignmentsRouter = require('./routes/module_assignments'); // 模块分配相关路由

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Token 验证中间件（除了登录和注册路由）
app.use((req, res, next) => {
  const publicPaths = [
    '/api/users/login', 
    '/api/users/register', 
    '/api/system/settings/list',
    '/api/users/roles' //用户角色列表也不需要token
  ];

  if (!publicPaths.some(path => req.path.startsWith(path))) {
    authMiddleware(req, res, next);
  } else {
    next();
  }
});

// 路由配置
app.use('/api/projects', projectRoutes);
app.use('/api/project-members', projectMembersRouter);
app.use('/api/tasks', taskRoutes);
app.use('/api/logs', logRoutes);
app.use('/api/users', userRoutes);
app.use('/api/modules', modulesRouter);
app.use('/api/bugs', bugsRouter);
app.use('/api/bug-comments', bugCommentsRouter);
app.use('/api/system', settingsRouter);
app.use('/api/performance', performanceRouter);
app.use('/api/module-assignments', moduleAssignmentsRouter);

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
